package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dto.WithdrawalApplyDTO;
import com.zhentao.pojo.UserBalance;
import com.zhentao.pojo.WithdrawalRecord;
import com.zhentao.service.UserBalanceService;
import com.zhentao.service.WithdrawalRecordService;
import com.zhentao.util.Result;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 提现记录控制器
 * 实现提现记录根据时间倒序排列查询
 */
@RestController
@RequestMapping("/withdrawal")
@CrossOrigin
public class WithdrawalRecordController {

    @Resource
    private UserBalanceService userBalanceService;

    @Resource
    private WithdrawalRecordService withdrawalRecordService;

    /**
     * 根据用户ID查询提现记录，按申请时间倒序排列
     * @param userId 用户ID
     * @return 提现记录列表
     */
    @GetMapping("/list")
    public Result getWithdrawalRecordsByUserId(@RequestParam String userId) {
        try {
            // 创建查询条件
            QueryWrapper<WithdrawalRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .orderByDesc("apply_time"); // 按申请时间倒序排列

            // 执行查询
            List<WithdrawalRecord> records = withdrawalRecordService.list(queryWrapper);

            return Result.OK(records);
        } catch (Exception e) {
            return Result.ERROR("查询提现记录失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询提现记录，按申请时间倒序排列
     * @param userId 用户ID
     * @param current 当前页码
     * @param size 每页大小
     * @return 分页提现记录
     */
    @GetMapping("/page")
    public Result getWithdrawalRecordsPage(
            @RequestParam String userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            // 创建分页对象
            Page<WithdrawalRecord> page = new Page<>(current, size);

            // 创建查询条件
            QueryWrapper<WithdrawalRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .orderByDesc("apply_time"); // 按申请时间倒序排列

            // 执行分页查询
            Page<WithdrawalRecord> result = withdrawalRecordService.page(page, queryWrapper);

            return Result.OK(result);
        } catch (Exception e) {
            return Result.ERROR("分页查询提现记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据状态查询提现记录，按申请时间倒序排列
     * @param userId 用户ID
     * @param status 状态：1-申请中，2-处理中，3-成功，4-失败
     * @return 提现记录列表
     */
    @GetMapping("/listByStatus")
    public Result getWithdrawalRecordsByStatus(
            @RequestParam String userId,
            @RequestParam Integer status) {
        try {
            // 创建查询条件
            QueryWrapper<WithdrawalRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("status", status)
                    .orderByDesc("apply_time"); // 按申请时间倒序排列

            // 执行查询
            List<WithdrawalRecord> records = withdrawalRecordService.list(queryWrapper);

            return Result.OK(records);
        } catch (Exception e) {
            return Result.ERROR("查询提现记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户提现统计信息
     * @param userId 用户ID
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public Result getWithdrawalStatistics(@RequestParam String userId) {
        try {
            // 查询所有提现记录
            QueryWrapper<WithdrawalRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            List<WithdrawalRecord> allRecords = withdrawalRecordService.list(queryWrapper);

            // 计算统计信息
            double totalAmount = 0.0;
            double successAmount = 0.0;
            int totalCount = allRecords.size();
            int successCount = 0;
            int processingCount = 0;
            int failedCount = 0;

            for (WithdrawalRecord record : allRecords) {
                totalAmount += record.getAmount().doubleValue();

                if (record.getStatus() == 3) { // 成功
                    successAmount += record.getAmount().doubleValue();
                    successCount++;
                } else if (record.getStatus() == 1 || record.getStatus() == 2) { // 申请中或处理中
                    processingCount++;
                } else if (record.getStatus() == 4) { // 失败
                    failedCount++;
                }
            }

            // 构建返回结果
            java.util.Map<String, Object> statistics = new java.util.HashMap<>();
            statistics.put("totalAmount", totalAmount);
            statistics.put("successAmount", successAmount);
            statistics.put("totalCount", totalCount);
            statistics.put("successCount", successCount);
            statistics.put("processingCount", processingCount);
            statistics.put("failedCount", failedCount);

            return Result.OK(statistics);
        } catch (Exception e) {
            return Result.ERROR("获取提现统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 立即提现申请（支持JSON方式提交）
     * @param dto 提现申请参数
     * @return 申请结果
     */
    @PostMapping("/apply")
    @Transactional(rollbackFor = Exception.class)
    public Result applyWithdrawal(@RequestBody WithdrawalApplyDTO dto) {
        try {
            String userId = dto.getUserId();
            BigDecimal amount = dto.getAmount();
            String bankCard = dto.getBankCard();
            String bankName = dto.getBankName();
            String realName = dto.getRealName();

            // 参数校验
            if (userId == null || userId.trim().isEmpty()) {
                return Result.ERROR("用户ID不能为空");
            }
            if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.ERROR("提现金额必须大于0");
            }
            if (amount.compareTo(new BigDecimal("10")) < 0) {
                return Result.ERROR("单笔提现最低金额为10元");
            }
            if (bankCard == null || bankCard.trim().isEmpty()) {
                return Result.ERROR("银行卡号不能为空");
            }
            if (bankName == null || bankName.trim().isEmpty()) {
                return Result.ERROR("银行名称不能为空");
            }
            if (realName == null || realName.trim().isEmpty()) {
                return Result.ERROR("持卡人姓名不能为空");
            }

            // 查询用户余额
            UserBalance userBalance = userBalanceService.getOne(
                new QueryWrapper<UserBalance>().eq("user_id", userId)
            );
            if (userBalance == null) {
                return Result.ERROR("用户余额信息不存在");
            }
            if (userBalance.getAvailableBalance().compareTo(amount) < 0) {
                return Result.ERROR("余额不足，无法提现");
            }

            // 扣减余额
            userBalance.setAvailableBalance(userBalance.getAvailableBalance().subtract(amount));
            userBalanceService.updateById(userBalance);

            // 新增提现记录
            WithdrawalRecord record = new WithdrawalRecord();
            record.setUserId(userId);
            record.setAmount(amount);
            record.setBankCard(bankCard);
            record.setBankName(bankName);
            record.setRealName(realName);
            record.setStatus(1); // 1-申请中
            record.setApplyTime(new Date());
            withdrawalRecordService.save(record);

            return Result.OK("提现申请已提交，请等待审核");
        } catch (Exception e) {
            return Result.ERROR("提现申请失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户当前可用余额
     * @param userId 用户ID
     * @return 用户余额信息
     */
    @GetMapping("/balance")
    public Result getUserBalance(@RequestParam String userId) {
        try {
            // 参数校验
            if (userId == null || userId.trim().isEmpty()) {
                return Result.ERROR("用户ID不能为空");
            }

            // 查询用户余额
            UserBalance userBalance = userBalanceService.getOne(
                new QueryWrapper<UserBalance>().eq("user_id", userId)
            );
            
            if (userBalance == null) {
                return Result.ERROR("用户余额信息不存在");
            }
            
            return Result.OK(userBalance);
        } catch (Exception e) {
            return Result.ERROR("查询用户余额失败：" + e.getMessage());
        }
    }
}
